<template>
  <div>
    <el-card>
      <el-form :model="form" size="mini" label-position="top" ref="form">
        <el-row :gutter="10">
          <el-col :lg="4" :md="6">
            <el-form-item label="机构名称" prop="BRANCHNO">            
              <select-tree :tree-data="treedata" :branch="form.branchName" @getBranchName="getBranch"></select-tree>
            </el-form-item>
          </el-col>
          <el-col :lg="4" :md="6">
            <el-form-item label="工作模式编号" prop="workId">
              <el-input v-model="form.workId" placeholder="请输入工作模式编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="4" :md="6">
            <el-form-item label="工作模式名称" prop="workName">
              <el-input v-model="form.workName" placeholder="请输入工作模式名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg='8' :md='12' class="searchBtnMarginTop">
            <el-button type="primary" icon="el-icon-search" @click="queryWorkModel" size='mini'>查询
            </el-button>
          <!-- </el-col>
          <el-col :lg="2" :md="3" class="searchBtnMarginTop"> -->
            <el-button type="warning" size="mini" icon="el-icon-refresh" @click="resetForm('form')">重置</el-button>
          <!-- </el-col>
          <el-col :lg="2" :md="3" class="searchBtnMarginTop"> -->
            <el-button type="primary" size="mini" @click="addWorkModel('add')" icon="el-icon-plus">新增工作模式</el-button>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="tableData" style="width: 100%;margin-top:10px;" :header-cell-style="tableHeaderStyle"
        :row-class-name="eventRowworkName">
        <el-table-column prop="CLASSESINFO" type="expand">
          <template slot-scope="scope">
            <div style="width:100%;overflow:scroll;">
            <table style="border:1px solid #fff;" class="tableStyle">
              <!-- 表头 -->
              <tr v-if="scope.row.WORKMODETYPE == 'week'">
                <th width="140">班次/日期</th>
                <th  width="100" v-for="(item,index) in scope.row.CLASSESINFO" :key="index">{{'星期'+item.DATENUM}}</th>
              </tr>
              <tr v-else>
                <th width="140" >班次/日期</th>
                <th  width="100" v-for="(item,index) in scope.row.CLASSESINFO" :key="index">{{ '&nbsp;&nbsp;'+item.DATENUM + '&nbsp;&nbsp;'}}</th>
              </tr>
              <!-- 固定列 -->
              <tr>
                <td width="140">是否可休假</td>
                <td v-for="(item,index) in scope.row.CLASSESINFO" :key="index">
                  <i class="el-icon-close" v-if="item.ISENABLEHOLIDAY =='0'"></i>
                  <i class="el-icon-check" v-if="item.ISENABLEHOLIDAY !='0'"></i>
                </td>
              </tr>
              <tr width="140" v-for="(item,index) in scope.row.arr" :key="index" v-if="item.CLASSESID != ''||item.CLASSESNAME!==null">
                <td>{{item.CLASSESNAME}}</td>
                <td v-for="(d_item,d_index) in scope.row.CLASSESINFO" :key="d_index">
                  <span v-html='formatString1(d_item.CLASSES,item)'></span>
                </td>

              </tr>
            </table>
            </div>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="50">
        </el-table-column>
        <el-table-column prop="WORKMODEID" label="工作模式编号" width="120">
        </el-table-column>
        <el-table-column prop="WORKMODENAME" label="工作模式名称" align="center">
        </el-table-column>
         <el-table-column prop="WORKMODETYPE" label="工作模式类型" align="center">
          <template slot-scope="scope">
            <div>
              {{scope.row.WORKMODETYPE == 'week'?'周模式':'月模式'}}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="CONSISTTOLER" label="一致性容差" align="center">
        </el-table-column>
        <el-table-column prop="NOTES" label="说明" align="center">
        </el-table-column>
        <el-table-column prop="OTINFO" label="关联加班名称" :formatter="OTINFOFormatter">
        </el-table-column>
        <el-table-column label="操作" align="center" width="120">
          <template slot-scope="scope">
            <el-button type="text" @click="addWorkModel('edit',scope.row)">修改</el-button>
            <el-button type="text" @click="delWork(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row>
        <el-col>
          <el-pagination style="text-align: right; margin-top:20px;" :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize" @size-change="handleInSizeChange" @current-change="handleInCurrentChange"
            :current-page="currpage" background layout="sizes, total, prev, pager, next, jumper" :total="tableTotal">
          </el-pagination>
        </el-col>
      </el-row>
      <component :is="dialogList.editDialog" :option="editOptions" @ListenClass="queryWorkModel"></component>

    </el-card>
  </div>
</template>
<script>
  import request from "@/common/utils/requestWFM";
  import selectTree from "@/components/selectTree5/";
  import Query from '@/message/wfm/scheduleDataManage/workModel/workQuery'
  import Del from '@/message/wfm/scheduleDataManage/workModel/workDel'
  import Update from '@/message/wfm/scheduleDataManage/workModel/workUpdate'
  import editDialog from './dialog/editDialog'
  import getGlobalParams from "@/common/utils/getGlobalParams";
  import branchQuery from '@/message/wfm/baseData/branchManage/branchQuery'

  export default {
    components: {
      selectTree
    },
    data() {
      return {
         defaultProps: {
          children: 'children',
          label: 'BRANCHNAME'
        },
        popoverShow: false,
        resData: "",
        treedata: [],
        tableTotal: 1,
        currpage: 1,
        pageSize: getGlobalParams.get("PageSize"),
        form: { //表单数据
          workId: "",
          workName: "",
          branchNO: this.$store.getters.BranchNum,
          branchName: this.$store.getters.BranchName
        },
        dialogList: {
          editDialog
        },
        tableData: [],
        editOptions: {
          isShow: false,
          title: '',
          row: {},
          treedata: []
        },
      }
    },
    created() {
      this.queryWorkModel()
      // this.queryBranch()
    },
    filters: {
      // formatString1(arr,item) {
      //   console.log('2222',arr)
      //   let array = []
      //   arr.forEach(item1 => {
      //     array.push(item1.CLASSESNAME)
      //   });
      //   return array.indexOf(item.CLASSESNAME) == -1?  '<i class="el-icon-close"></i>': '<i class="el-icon-check"></i>'
      // },
    },
    methods: {
      formatString1(arr,item) {
        let array = []
        arr.forEach(item1 => {
          array.push(item1.CLASSESNAME)
        });
        return array.indexOf(item.CLASSESNAME) == -1? '<i class="el-icon-close"></i>': '<i class="el-icon-check"></i>'
        // return array.indexOf(item) == -1? 'y': 'n'
      },
       getBranch(data) {
        // console.log(data)
        this.form.branchName = data.BRANCHNAME
        this.form.branchNO = data.BRANCHNO
        // this.ruleForm.branchNO = data.BRANCHNO
        this.popoverShow = false
      },
      OTINFOFormatter(row, column){
        let array = []
        row.OTINFO.forEach(item => {
          array.push(item.OTNAME)
        });
        return array.join(',')
      },
      resetForm(formName) { //重置查询表单
        this.$refs["" + formName].resetFields();
        // this.checkedIds = [];
      },
      // 新增/修改工作模式
      addWorkModel(op,row) {
        if(op == 'add'){
          this.editOptions.isShow = true
          this.editOptions.title = '新增工作模式'
          this.editOptions.treedata = this.treedata
        }else if(op == 'edit'){
          this.tableData.forEach(item => {
            let holiday = [];
            item.CLASSESINFO.forEach(i => {
              if(i.ISENABLEHOLIDAY != '0'){
                holiday.push(i.DATENUM);
              }
            })
            item.holiday = holiday;
          });
          this.editOptions.isShow = true
          this.editOptions.title = '修改工作模式'
          this.editOptions.row = row
          this.editOptions.treedata = this.treedata
          this.editOptions.row.branchNO = this.form.branchNO
          this.editOptions.row.branchName = this.form.branchName
        }else{
          console.log('submit error');
        }
      },
       compare(property) {
        return function (a, b) {
          var value1 = a[property];
          var value2 = b[property];
          return value1 - value2;
        }
      },
      // 工作模式查询
      async queryWorkModel() {
        let resBody = new Query()
        resBody.data.BRANCHNO = this.form.branchNO
        resBody.data.WORKMODEID = this.form.workId
        resBody.data.WORKMODENAME = this.form.workName
        resBody.data.CurrPage = this.currpage;
        resBody.data.PageRowNum = this.pageSize;
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.tableTotal = response.BODY.TotalRowNum;
          this.tableData = response.BODY.RSPSTRUCT
          this.tableData.forEach(item => {
            item.CLASSESINFO.sort(this.compare("DATENUM"))
          })
          this.tableData.forEach(item => {
            let arr = [];
            let holiday = [];
            item.CLASSESINFO.forEach(i => {
              i.CLASSES.forEach(e => {
                arr.push(e)
              })
            })
            var obj = {};
              arr = arr.reduce(function(item, next) {
                obj[next.CLASSESID] ? '' : obj[next.CLASSESID] = true && item.push(next);
                return item;
            }, []);
            // var allArr = []
            // $.each(arr,function(i,v){
            //   var flag = true;
            //   if(allArr.length > 0){
            //       $.each(allArr,function(n,m){
            //           if(allArr[n].CLASSESID == arr[i].CLASSESID){flag = false;};
            //       });
            //   };
            //   if(flag){
            //       allArr.push(arr[i]);
            //   };
            // });
            arr.forEach((item,index) => {
              if(item.CLASSESNAME == null){
                arr.splice(index,1)
              }
            })
            item.arr = arr;
          });
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },
      //前端分页
      handleInCurrentChange(val) {
        this.currpage = val;
        this.queryWorkModel()
      },
      handleInSizeChange(val) {
        this.pageSize = val;
        this.queryWorkModel()
      },
      // 删除工作模式
      delWork(row) {
        this.$confirm('此操作将删除该工作模式, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let resBody = new Del()
          resBody.data.WORKMODEID = row.WORKMODEID
          let response = await request(resBody);
          if (response.SYS_HEAD.ReturnCode == "000000") {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.queryWorkModel()
          } else {
            this.$message({
              type: "error",
              message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
            })
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        })
      },
      eventRowworkName(
        row,
        rowIndex
      ) {
        return 'success-row'
      },
      tableHeaderStyle({
        row,
        column,
        rowIndex,
        columnIndex
      }) {
        return 'background-color:#C1E0B8;'
      }
    },
  }

</script>

<style lang="scss">
.tableStyle{
.expand .el-table__expand-column .cell {
    display: none;
  }

  .el-table .warning-row {
    background: #e4e1e1;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }

  .el-table__expanded-cell {
    padding: 0 !important;
  }

  .expand_table{
    width: 100%;
    border-collapse: collapse;
  }
  .el-icon-check{
    color: #67C23A;
  }
  .el-icon-close{
    color:  #F56C6C;
  }
}
 

</style>
<style lang="scss" scoped>
  .tableStyle{
    width: 100%;
    border: 1px solid #aeb0b1;
    text-align: center;
  }
  .el-table th{
    text-align: center !important;
  }
  .el-table td{
    text-align: center !important;
    width: 120px;
  } 
</style>
